<?php
/* PHP SDK
 * @version 1.0.0
 * @author 星星不亮了丶 yykkk@vip.qq.com
 * @copyright © 2013, Tencent Corporation. All rights reserved.
 */

/*
 * @brief QC类，api外部对象，调用接口全部依赖于此对象
 * */
//namespace lib;

class WX
{
    const VERSION = "1.0";
    const GET_AUTH_CODE_URL = "https://open.weixin.qq.com/connect/qrconnect";
    const GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token";
    const GET_USER_INFO_URL = "https://api.weixin.qq.com/sns/userinfo";

    public function __construct($appid, $appkey)
    {
        global $siteurl;
        $this->appid = $appid;
        $this->appkey = $appkey;
        $this->callback = $siteurl . 'return.php';
    }

    public function wx_login($state)
    {

        //-------构造请求参数列表
        $keysArr = array(
            "response_type" => "code",
            "appid" => $this->appid,
            "redirect_uri" => $this->callback,
            "state" => $state,
            "scope" => "snsapi_login",
        );

        $login_url = self::GET_AUTH_CODE_URL . '?' . http_build_query($keysArr);

        return $login_url;
    }

    public function wx_callback($code)
    {
        //-------请求参数列表
        $keysArr = array(
            "grant_type" => "authorization_code",
            "appid" => $this->appid,
            "secret" => $this->appkey,
            "code" => $code,
        );

        //------构造请求access_token的url
        $token_url = self::GET_ACCESS_TOKEN_URL . '?' . http_build_query($keysArr);
        $response = json_decode($this->get_curl($token_url), true);
        if (!empty($response['errcode'])) {
            exit(json_encode(array('code' => -1, 'errcode' => $response['errcode'], 'msg' => $response['errmsg'])));
        }

        return $response;
    }

    public function get_userinfo($openid, $access_token)
    {

        //-------请求参数列表
        $keysArr = array(
            "access_token" => $access_token,
            "openid" => $openid,
        );

        $graph_url = self::GET_USER_INFO_URL . '?' . http_build_query($keysArr);
        $response = json_decode($this->get_curl($graph_url), true);
        if (!empty($response['errcode'])) {
            exit(json_encode(array('code' => -1, 'errcode' => $response['errcode'], 'msg' => $response['errmsg'])));
        } else {
            return $response;
        }
    }

    public function get_curl($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Linux; U; Android 4.4.1; zh-cn) AppleWebKit/533.1 (KHTML, like Gecko)Version/4.0 MQQBrowser/5.5 Mobile Safari/533.1');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        $ret = curl_exec($ch);
        curl_close($ch);
        return $ret;
    }
}
